package naga.x.platform2.support;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;

import naga.x.platform2.utils.IOUtils;

/**
 * 重写read方法，不用json解析InputStream, byte[]<br/>
 * 重写writeInternal方法，不用json序列化String
 * @author yang.li
 *
 */
public class FastJsonHttpMessageConverterImpl extends FastJsonHttpMessageConverter4 {
	
	@Override
	public Object read(Type type, Class<?> contextClass,
			HttpInputMessage inputMessage) throws IOException,
			HttpMessageNotReadableException {
		if (type instanceof Class) {
			if (InputStream.class.isAssignableFrom((Class<?>) type)) {
				return inputMessage.getBody();
			}
			if (type == byte[].class) {
				InputStream body = inputMessage.getBody();
				ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
				byte[] buf = new byte[128];
				int len;
				while ((len = body.read(buf)) != -1) {
					out.write(buf, 0, len);
				}
				return out.toByteArray();
			}
		}
		return super.read(type, contextClass, inputMessage);
	}

	@Override
	protected void writeInternal(Object obj, Type type, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		HttpHeaders headers = outputMessage.getHeaders();
//		'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'
		headers.add("Access-Control-Allow-Origin", "*");
		if (type == String.class || obj instanceof CharSequence) {
			byte[] b = IOUtils.getStringBytes(obj.toString(), getFastJsonConfig().getCharset());
			if (b != null) {
				headers.setContentLength(b.length);
				OutputStream out = outputMessage.getBody();
				out.write(b);
			}
			return;
		}
		super.writeInternal(obj, type, outputMessage);
	}

}
